package com.soft.mainsite.common.template;

import com.google.common.collect.Lists;
import com.soft.mainsite.common.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;

/**
 * Description:
 *
 * @author Jin
 * @create 2017-08-11
 */
@Slf4j
@Service
public class TemplateFileServiceImpl implements TemplateFileService {

    private String TEMPLATE_PATH = null;

    private final String HTML = ".html";

    @Value("${system.template.path}")
    private String staticResourceTemplatePath;

    @Value("${system.site.static.path}")
    public void setTEMPLATE_PATH(String path){
        TEMPLATE_PATH = path + File.separator + "templates" + File.separator + "www";
    }

    @Override
    public List<TemplateFile> findAll() {
        List<TemplateFile> result = Lists.newArrayList();
        File mainFile = new File(TEMPLATE_PATH);
        log.info("读取文件路径：" + TEMPLATE_PATH);
        if (!mainFile.exists() || mainFile.listFiles().length < 1) {
            throw new SystemException("请检查模板目录是否存在！");
        }
        /*遍历了四级目录，前端页面目录结构要一致（也要遍历四级目录）*/
        for (File file : mainFile.listFiles()) {
            // 第一层  mobile xgwy
            TemplateFile templateFile = new TemplateFile();
            templateFile.setFileName(file.getName());
            templateFile.setFilePath(file.getAbsolutePath());
            templateFile.setIsDirectory(file.isDirectory());
            if (file.isDirectory()) {
                File subFile = new File(file.getAbsolutePath());
                List<TemplateFile> childList = Lists.newArrayList();
                for (File subfile : subFile.listFiles()) {
                    // 第二层
                    TemplateFile subTemplateFile = new TemplateFile();
                    subTemplateFile.setFileName(subfile.getName());
                    subTemplateFile.setFilePath(subfile.getAbsolutePath());
                    subTemplateFile.setIsDirectory(subfile.isDirectory());
                    if (subfile.isDirectory()) {
                        List<TemplateFile> subChildList = Lists.newArrayList();
                        File subChildFile = new File(subfile.getAbsolutePath());
                        if (!subChildFile.exists() || subFile.listFiles().length < 1) {
                            continue;
                        }
                        for (File subChildfile : subChildFile.listFiles()) {
                            // 第三层
                            TemplateFile subChildTemplateFile = new TemplateFile();
                            subChildTemplateFile.setFileName(subChildfile.getName());
                            subChildTemplateFile.setFilePath(subChildfile.getAbsolutePath());
                            subChildTemplateFile.setIsDirectory(subChildfile.isDirectory());
                            if (subChildfile.isDirectory()) {
                                List<TemplateFile> thirdChildList = Lists.newArrayList();
                                File thirdChildFile = new File(subChildfile.getAbsolutePath());
                                if (!thirdChildFile.exists() || subChildFile.listFiles().length < 1) {
                                    continue;
                                }
                                for (File thirdChildfile : thirdChildFile.listFiles()) {
                                    TemplateFile thirdChildTemplateFile = new TemplateFile();
                                    thirdChildTemplateFile.setFileName(thirdChildfile.getName());
                                    thirdChildTemplateFile.setFilePath(thirdChildfile.getAbsolutePath());
                                    thirdChildTemplateFile.setIsDirectory(thirdChildfile.isDirectory());
                                    thirdChildList.add(thirdChildTemplateFile);
                                }
                                subChildTemplateFile.setChildList(thirdChildList);
                            }
                            subChildList.add(subChildTemplateFile);
                        }
                        subTemplateFile.setChildList(subChildList);
                    }
                    childList.add(subTemplateFile);
                }
                templateFile.setChildList(childList);
            }
            result.add(templateFile);
        }
        return result;
    }

    @Override
    public TemplateFile findByPath(String path) {
        File file = new File(path);
        if (!file.exists()) {
            throw new SystemException("模板不存在请检查！");
        }
        String parentPath = null;
        String[] fileParent = file.getParent().split("templates");
        if (fileParent.length == 1){
            parentPath = File.separator;
        }else {
            parentPath = fileParent[1];
        }
        TemplateFile templateFile = new TemplateFile();
        templateFile.setFileName(file.getName());
        templateFile.setFilePath(file.getAbsolutePath());
        templateFile.setParentPath(parentPath);
        templateFile.setContent(this.readTemplateFileContent(file));
        return templateFile;
    }


    public static void main(String[] args) {
        List<TemplateFile> list = new TemplateFileServiceImpl().findAll();
        for (TemplateFile templateFile : list) {
            System.out.println(templateFile.getFileName());
            if (templateFile.getIsDirectory()) {
                for (TemplateFile t : templateFile.getChildList()) {
                    System.out.println(templateFile.getFileName() + "---->" + t.getFileName() + "[" + t.getFilePath() + "]");
                    if (t.getIsDirectory()) {
                        for (TemplateFile st : t.getChildList()) {
                            System.out.println(templateFile.getFileName() + "/" + t.getFileName() + "---------->" + st.getFileName() + "[" + st.getFilePath() + "]");
                            if (st.getIsDirectory()) {
                                for (TemplateFile tt : st.getChildList()) {
                                    System.out.println(templateFile.getFileName() + "/" + t.getFileName() + "/" + st.getFileName() + "---------->" + tt.getFileName() + "[" + tt.getFilePath() + "]");
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public String readTemplateFileContent(File file) {
        ByteArrayOutputStream bos = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }

        } catch (Exception e) {
            throw new SystemException(e.getMessage());
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                log.error("读取模板失败");
            }

            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("读取模板失败, {}", e);
            }
        }
        try {
            return new String(bos.toByteArray(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("读取模板失败");
        }

        return "";
    }

    @Override
    @Async
    public void writeTemplateFileContent(TemplateFile templateFile) {
        try {
            OutputStream outputStream = new FileOutputStream(new File(templateFile.getFilePath()));
            OutputStreamWriter os = new OutputStreamWriter(outputStream, "utf-8");
            os.write(templateFile.getContent());
            os.flush();
            os.close();
        } catch (Exception e) {
            throw new SystemException(e.getMessage());
        }
    }


    @Override
    public Boolean deleteByPath(String path) {
        File file = new File(path);
        if (!file.exists()){
            throw new SystemException("模板不存在，请检查！");
        }
        log.info("删除的模板为： {}", file);
        return file.delete();
    }

    @Async
    @Override
    public void saveTemplateFileNameAndPath(TemplateFile templateFile) {
        String fileName = templateFile.getFileName();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        log.info("模板名称为： " + fileName);
        log.info("新增的模板类型为：" + fileType);

        if (!HTML.equals(fileType)){
            throw new SystemException("模板类型错误！请使用h5类型的模板再试！");
        }
        String parentPath = templateFile.getParentPath();
        log.info("模板父级目录为： " + parentPath);

        File dest = new File(getStaticResourceTemplatePath() + parentPath + File.separator + fileName);
        File destFile = new File(getStaticResourceTemplatePath() + parentPath);
        if (!destFile.exists()){
            destFile.mkdirs();
        }

        log.info("父文件为： " + dest.getParentFile());
        log.info("getAbsoluteFile： " + destFile.getAbsoluteFile());
        cn.hutool.core.io.file.FileWriter writer = new cn.hutool.core.io.file.FileWriter(dest);
        writer.write(templateFile.getContent());
    }

    @Override
    public void add(MultipartFile[] files, String parentPath) {

        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            log.info("上传的模板文件名为：" + originalFilename);

            // 获取文件类型
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
            log.info("上传的模板文件类型为：" + fileType);

            if (!HTML.equals(fileType)){
                throw new SystemException("模板类型错误！请使用h5类型的模板再试！");
            }

            // 文件上传路径
            String staticResourcePath = getStaticResourceTemplatePath();
            log.info("模板上传的根目录：" + staticResourcePath + parentPath);
            File dest = new File(staticResourcePath + parentPath + File.separator + originalFilename);
            if (!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                log.error("模板文件上传异常，{}", e.getMessage());
                e.printStackTrace();
            }
        }

    }

    private String getStaticResourceTemplatePath(){
        StringBuilder sb = new StringBuilder();
        return sb.append(staticResourceTemplatePath).toString().replaceAll("\\\\", "/");
    }
}
